#!/usr/bin/python
#coding=utf-8
import json
import smtplib
import time
import xlrd
from datetime import date
from email.header import Header
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from util.log import Log


class SendEmail:

    def __init__(self, report):
        self.file_path = report
        self.workbook = xlrd.open_workbook(self.file_path)
        with open("../dataconfig/config.json", "r+", encoding='utf-8') as f:
            self.run_config = json.load(f)

    def send_mail(self):
        # 定义收件人与发件人
        sender = self.run_config['email']['email_user']
        password = self.run_config['email']['email_password']
        receivers = self.run_config['email']['receivers']
        smpt_address = self.run_config['email']['smpt_address']
        smpt_port = self.run_config['email']['smpt_port']

        # 邮件正文内容
        msg = MIMEMultipart()
        # 添加邮件主题
        msg['Subject'] = Header('接口自动化测试报告' + time.strftime('%Y/%m/%d'), 'utf-8')
        # 添加收件人与发件人
        msg['from'] = sender
        msg['to'] = receivers
        #整合结果文件report
        content = self.mailWrite()
        cs = """
        <p>本次接口测试结果如下：</p>
        """
        contents = cs + content
        html = MIMEText(contents, 'html', 'utf-8')
        msg.attach(html)

        #附件
        part = MIMEApplication(open(self.file_path, 'rb').read())
        # filename=邮件附件中显示的文件的名称，可自定义
        filename = "接口测试报告"+time.strftime("%Y-%m-%d")+".xls"
        part.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(part)

        self.log = Log()

        try:
            # 实例化邮件
            smtp = smtplib.SMTP()
            smtp.connect(smpt_address, port=int(smpt_port))
            # 调用登录
            smtp.login(sender, password)
            # 发送邮件
            smtp.sendmail(sender, receivers.split(','), msg.as_string())
            self.log.log('INFO', 'e-mail has send out!')
            smtp.quit()
        except BaseException as e:
            self.log.log('ERROR', e)

    def mailWrite(self):
        part1 = '''<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <style>
table{
border:1px;
cellspacing:0;
cellpadding:3;
bordercolor:#000000;
width:50%;
align:left;
frame:void;
rules:none;
}

.pie38{width: 100px;height: 100px;border-radius: 50px;margin:20px;background-color: #ddd;position: relative;display: inline-block;overflow: hidden}
.pie38 .pie_content{line-height: 100px;text-align: center;position: absolute;width: 100px;height: 100px;z-index: 8}
.pie38 .pie_left{position: absolute;top:0;left:0;width: 50px;height: 100px;overflow: hidden;}
.pie38 .pie_left:after{content: '';height: 100px;width:50px;border-right:50px solid red;position:absolute;top:0;left:0;transform: rotate(-'''

        part2 = ''     # 百分比换算的角度
        part3 = '''deg);}
        </style>

    </head>

    <body text="#000000" >
    <div style="width:60%">
        <div>
            <table class="table">'''

        part4 = ''  # 汇总统计表
        part5 = '''</table>
        </div>
        <div class="pie38">
         <div class="pie_content">'''

        part6 = ''  # 百分比
        part7 = '''</div>
         <div class="pie_left"></div>
        </div>
    </div>
    <div>
        <table border="1" cellspacing="0" cellpadding="3" bordercolor="#000000" align="left" style="width:45%;">
            '''

        part8 = ''    # 详细统计表
        part9 = '''        </table>
    </div>

    </body>
</html>'''

        # 打开汇总sheet页
        sheet = self.workbook['config']

        part6 = sheet.cell_value(10, 1)

        part2 = str(int(sheet.cell_value(10, 1).split("%")[0])*360)

        for i in range(4, 11):
            td = ''
            for j in range(0, sheet.ncols):
                if i == 4 and j == 1:
                    date_value = xlrd.xldate_as_tuple(sheet.cell_value(i, j), 0)
                    cellData = date(*date_value[:3]).strftime('%Y/%m/%d')
                    tip = '<td> ' + cellData + '</td>'
                    td = td + tip
                else:
                    cellData = str(sheet.cell(i, j).value)
                    tip = '<td colspan="4"> ' + cellData + '</td>'
                    td = td + tip
            part4 = part4 + '<tr>' + td + '</tr>'

        for i in range(11, sheet.nrows):
            td = ''
            for j in range(0, sheet.ncols):
                if i == 11:
                    tip = '<td colspan="5" align="center"><b>' + "详细统计" + '<b></td>'
                    td = td + tip
                    break
                else:
                    cellData = str(sheet.cell(i, j).value)
                    tip = '<td> ' + cellData + '</td>'
                    td = td + tip
            part8 = part8 + '<tr>' + td + '</tr>'

        mailcontent = part1 + part2 + part3 + part4 + part5 + part6 + part7 + part8 + part9
        # 将excel文件的内容转换为html格式，后续在邮件中拼接
        return mailcontent

if __name__ == '__main__':
    sendemail = SendEmail("D:\\b_Auto\\automagic\\interfaceAPI\\result\\result_2021-10-15-12_11_50.xls")
    sendemail.send_mail()

